<?php
/***************************************************************************
 *                             pirep_submit.php
 *                            -------------------
 *                       (APU) Automated Pilot Utility
 *   begin                : Tuesday, Nov 9, 2004 - v 2.0 Tuesday Nov 21, 2006
 *   copyright            : (C) 2004-2006 SF Games
 *   email                : techsupport@sf-games.com
 *
 *   Expects the following POST variables:
 *
 *          PILOT ID #: pilot_id		<required>
 *            Password: pilot_pass		<required>
 *                Date: flight_date		<required>
 *       Aircraft Type: ac_type			<required>
 *              Tail #: tail_num		<required>
 *            Flight #: flight_num		<required>
 *   Departure Airport: departure		<required>
 * Destination Airport: destination		<required>
 *            Time Out: time_out		<required>
 *             Time In: time_in			<required>
 *            Fuel Out: fuel_out		<required>
 *             Fuel In: fuel_in			<required>
 *         PAX Carried: pax				<optional>
 *       Cargo Carried: cargo			<optional>
 *            Comments: comments		<optional>
 ***************************************************************************/

	include_once('common.php');
	include_once('config.php');
	include_once('dbcommon.php');
	include_once('randomQuote.php');

	// Page generation timer start.
	$time = microtime();
	$time = explode(" ", $time);$time = $time[1] + $time[0];$start = $time;

	// Global
	$aErrors = array();

	// Local variables
	$posted = array("PILOT_ID" => "", "PASSWORD" => "", "DATE" => "", "AC_TYPE" => "", "TAIL_NUM" => "", "FLIGHT_NUM" => "", "DEPART_ICAO" => "", "DEST_ICAO" => "", "TIME_OUT" => "", "TIME_IN" => "", "FUEL_OUT" => "", "FUEL_IN" => "", "PAX" => "", "CARGO" => "", "COMMENTS" => "", "PIREP_ID" => 0, "EDIT_MODE" => 0);
	$referrer = $_POST["referrer"];

	// Connect our database
	$db = mysql_connect($dbhost, $dbuname, $dbpass)
		or die("Error: in pirep_submit.php. Could not connect to the SQL server " .mysql_error());
	mysql_select_db($dbname);

	htmlHeader();

	// Gather Form POST variables and validate
	$posted = gatherPost($posted);

	// Validate posted variables
	validatePost($posted);

	// Validate user id / password combo
	if ( validateUser($posted["PILOT_ID"], $posted["PASSWORD"]) == false )
		array_push($aErrors, "The Pilot ID and or Password given, is incorrect");
	$posted["PASSWORD"] = "";

	// Calculate flight time
	$flightTime = calculateFlightTime($posted["DATE"], $posted["TIME_OUT"], $posted["TIME_IN"], isHelicopter($posted["AC_TYPE"]));

	// Determine fuel consumption
	$fuelBurn = calculateFuelBurn($posted["FUEL_OUT"], $posted["FUEL_IN"]);

	// Display any errors from the above functions
	if ( count($aErrors) > 0 )
	{
		echo "	<table class=\"table_roster_footer\">\n";
		echo "	<tbody>\n";
		echo "		<tr>\n";
		echo "			<td><span class=\"textred\">\n";
		echo "<div class=\"textdarkCenter\">There are " .count($aErrors) ." submission errors found!<br /><br /></div>\n";

		foreach ($aErrors as $sErr)
			echo $sErr ."<br />\n";

		echo "<div class=\"textdarkCenter\"><br />Press your browsers back button <a href=\"" .$referrer ."\">or here</a> and correct the invalid entries.<br /><br /></div>\n";
		echo "</span></td>\n";
		echo "		</tr>\n";
		echo "	</tbody>\n";
		echo "	<tfoot><tr><td colspan=\"1\"></td></tr></tfoot>\n";
		echo "	</table>\n";
	}
	else
	{
		// Add PIREP
		addPirep($posted, $flightTime, $fuelBurn);

		// Update pilot and get any promotion information
		$promotion = updatePilot($posted, $flightTime);

		// Display PIREP
		displayPirep($posted, $flightTime, $fuelBurn, $promotion);

		// Send an email to pilot with PIREP information submitted
		sendPirepEmail($posted, $flightTime, $fuelBurn, $promotion);
	}

	// End page timing
	$time = microtime();$time = explode(" ", $time);$time = $time[1] + $time[0];
	$finish = $time;$totaltime = ($finish - $start);
	$quote = new RandomQuote;
	printf ("This page %s in %f seconds<br/><br/>", $quote->getQuote(), $totaltime);

	htmlFooter();

 ?>


<?php

			///////////////////////////////////////////
			//                                       //
			//          Support Functions            //
			//                                       //
			///////////////////////////////////////////

//
// Display HTML header
//
function htmlHeader()
{
	echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
	echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
	echo "<head>\n";
	echo "<title>APU PIREP Submit</title>\n";
	include_once('header.php');

	echo "<style type=\"text/css\" media=\"screen\"> <!-- @import url(apu.css); --> </style>\n";

	echo "</head>\n";
	echo "<body>\n";
	echo "<div align=\"center\">\n";
}

//
// Display HTML footer
//
function htmlFooter()
{
	global $rosterNavigateTo;
	global $rosterNavigateVerbiage;
	global $APU_COPYRIGHT;

	// Display return to another page link/table
	echo "	<table class=\"table_roster_footer\">\n";
	echo "	<tbody>\n";
	echo "		<tr>\n";
	echo "			<td><div align=\"center\"><span class=\"textdark\">Click <a href=\"../" .$rosterNavigateTo ."\">here</a> " .$rosterNavigateVerbiage ."</span></div></td>\n";
	echo "		</tr>\n";
	echo "	</tbody>\n";
	echo "	<tfoot><tr><td colspan=\"1\"></td></tr></tfoot>\n";
	echo "	</table>\n";

	// Display Copyright
	echo "<p>" .$APU_COPYRIGHT ."</p>\n";

	// End HTML
	echo "</div>\n";
	echo "</body>\n";
	echo "</html>\n";
}

//
// Gather POSTed variables from the form submission
//
// Function validates lengths of required variables, strips any HTML and PHP and trims
// the string of leading and trailing white space.
//
// The global $aErrors may contain zero or more errors if any are found.
//
function gatherPost($posted)
{
	include('config.php');
	include('commondefs.php');	// include_once no workie for some dumb reason here. $MAX_ID_LENGTH will not be anything
	global $aErrors;

	if ( isset($_POST['pilot_id']) )
	{
		if ( strlen($_POST['pilot_id']) > 0 && strlen($_POST['pilot_id']) <= $MAX_ID_LENGTH )
		{
			$posted['PILOT_ID'] = strip_tags($_POST['pilot_id']);
			$posted['PILOT_ID'] = trim($posted['PILOT_ID']);

			if ( $bCapitalizedID )
				$posted['PILOT_ID'] = strtoupper($posted['PILOT_ID']);
		}
		else
			array_push($aErrors, "Your Pilot ID is empty or exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['pilot_pass']) )
	{
		if ( strlen($_POST['pilot_pass']) > 0 && strlen($_POST['pilot_pass']) <= $MAX_PASSWORD_LENGTH )
		{
			$posted["PASSWORD"] = strip_tags($_POST['pilot_pass']);
			$posted["PASSWORD"] = trim($posted["PASSWORD"]);
		}
		else
			array_push($aErrors, "Your Password is empty or exceeds the allowed length of " .$MAX_PASSWORD_LENGTH);
	}

	if ( isset($_POST['flight_date']) )
	{
		if ( strlen($_POST['flight_date']) > 0 && strlen($_POST['flight_date']) <= $MAX_DATE_LENGTH )
		{
			$posted["DATE"] = strip_tags($_POST['flight_date']);
			$posted["DATE"] = trim($posted["DATE"]);

			// Verify date from common.php function
			if ( verifyDate($posted["DATE"], $bUseEuroDateFormat) == TRUE )
			{
				// Convert to a mySQL date format of YYYY-MM-DD
				$posted["DATE"] = dateToMySQL($posted["DATE"], $bUseEuroDateFormat);
			}
			else
				array_push($aErrors, "The flight date you have given is not valid");
		}
		else
			array_push($aErrors, "The flight date you have given is not valid");
	}

	if ( isset($_POST['ac_type']) )
	{
		if ( strlen($_POST['ac_type']) > 0 && strlen($_POST['ac_type']) <= $MAX_OTHER_LENGTH )
		{
			$posted["AC_TYPE"] = strip_tags($_POST['ac_type']);
			$posted["AC_TYPE"] = trim($posted["AC_TYPE"]);
		}
		else
			array_push($aErrors, "Your Aircraft Type is empty or exceeds the allowed length of " .$MAX_OTHER_LENGTH);
	}

	if ( isset($_POST['tail_num']) )
	{
		if ( strlen($_POST['tail_num']) > 0 && strlen($_POST['tail_num']) <= $MAX_ID_LENGTH )
		{
			$posted["TAIL_NUM"] = strip_tags($_POST['tail_num']);
			$posted["TAIL_NUM"] = trim($posted["TAIL_NUM"]);
		}
		else
			array_push($aErrors, "Your Tail Number is empty or exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['flight_num']) )
	{
		if ( strlen($_POST['flight_num']) > 0 && strlen($_POST['flight_num']) <= $MAX_ID_LENGTH )
		{
			$posted["FLIGHT_NUM"] = strip_tags($_POST['flight_num']);
			$posted["FLIGHT_NUM"] = trim($posted["FLIGHT_NUM"]);
		}
		else
			array_push($aErrors, "Your Flight Number is empty or exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['departure']) )
	{
		if ( strlen($_POST['departure']) > 0 && strlen($_POST['departure']) <= $MAX_AIRPORT_ID )
		{
			$posted["DEPART_ICAO"] = strip_tags($_POST['departure']);
			$posted["DEPART_ICAO"] = trim($posted["DEPART_ICAO"]);
		}
		else
			array_push($aErrors, "The departure airport is empty or exceeds the allowed length of " .$MAX_AIRPORT_ID);
	}

	if ( isset($_POST['destination']) )
	{
		if ( strlen($_POST['destination']) > 0 && strlen($_POST['destination']) <= $MAX_AIRPORT_ID )
		{
			$posted["DEST_ICAO"] = strip_tags($_POST['destination']);
			$posted["DEST_ICAO"] = trim($posted["DEST_ICAO"]);
		}
		else
			array_push($aErrors, "The destination airport is empty or exceeds the allowed length of " .$MAX_AIRPORT_ID);
	}

	if ( isset($_POST['time_out']) )
	{
		if ( strlen($_POST['time_out']) > 0 && strlen($_POST['time_out']) <= $MAX_TIME_LENGTH )
		{
			$posted["TIME_OUT"] = strip_tags($_POST['time_out']);
			$posted["TIME_OUT"] = trim($posted["TIME_OUT"]);
		}
		else
			array_push($aErrors, "The time out is empty or exceeds the allowed length of " .$MAX_TIME_LENGTH);
	}

	if ( isset($_POST['time_in']) )
	{
		if ( strlen($_POST['time_in']) > 0 && strlen($_POST['time_in']) <= $MAX_TIME_LENGTH )
		{
			$posted["TIME_IN"] = strip_tags($_POST['time_in']);
			$posted["TIME_IN"] = trim($posted["TIME_IN"]);
		}
		else
			array_push($aErrors, "The time in is empty or exceeds the allowed length of " .$MAX_TIME_LENGTH);
	}

	if ( isset($_POST['fuel_out']) )
	{
		if ( strlen($_POST['fuel_out']) > 0 && strlen($_POST['fuel_out']) <= $MAX_ID_LENGTH )
		{
			$posted["FUEL_OUT"] = strip_tags($_POST['fuel_out']);
			$posted["FUEL_OUT"] = trim($posted["FUEL_OUT"]);
		}
		else
			array_push($aErrors, "The fuel out is empty or exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['fuel_in']) )
	{
		if ( strlen($_POST['fuel_in']) > 0 && strlen($_POST['fuel_in']) <= $MAX_ID_LENGTH )
		{
			$posted["FUEL_IN"] = strip_tags($_POST['fuel_in']);
			$posted["FUEL_IN"] = trim($posted["FUEL_IN"]);
		}
		else
			array_push($aErrors, "The fuel in is empty or exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['pax']) )
	{
		$posted["PAX"] = strip_tags($_POST['pax']);
		$posted["PAX"] = trim($posted["PAX"]);
		$posted["PAX"] = ereg_replace("[^0-9]", "", $posted["PAX"]);	// Remove alpha symbols

		if ( strlen($posted["PAX"]) > $MAX_ID_LENGTH )
			array_push($aErrors, "The number of passengers (Pax) exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['cargo']) )
	{
		$posted["CARGO"] = strip_tags($_POST['cargo']);
		$posted["CARGO"] = trim($posted["CARGO"]);
		$posted["CARGO"] = ereg_replace("[^0-9]", "", $posted["CARGO"]);	// Remove alpha symbols

		if ( strlen($posted["CARGO"]) > $MAX_ID_LENGTH )
			array_push($aErrors, "The amount of cargo exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	if ( isset($_POST['comments']) )
	{
		$posted["COMMENTS"] = strip_tags($_POST['comments']);
		$posted["COMMENTS"] = trim($posted["COMMENTS"]);

		if ( strlen($posted["COMMENTS"]) > $MAX_COMMENTS_LENGTH )
			array_push($aErrors, "Your comments exceeds the allowed length of " .$MAX_COMMENTS_LENGTH);
	}

	if ( isset($_POST['pirepID']) )
	{
		$posted["PIREP_ID"] = strip_tags($_POST['pirepID']);
		$posted["PIREP_ID"] = trim($posted["PIREP_ID"]);
	}

	if ( isset($_POST['editmode']) )
	{
		$posted["EDIT_MODE"] = strip_tags($_POST['editmode']);
		$posted["EDIT_MODE"] = trim($posted["EDIT_MODE"]);
	}

	return $posted;
}

//
// Validate other PIREP posted values for sanity
//
function validatePost($posted)
{
	include_once('config.php');
	global $aErrors;

	// Check Fuel out and in sanity
	if ( !$bAllowFuelInGTFuelOut )
	{
		if ( $posted["FUEL_IN"] > $posted["FUEL_OUT"] )
			array_push($aErrors, "Your fuel in is greater than the fuel when you departed");
	}

	if ( $posted["FUEL_OUT"] == 0 )
		array_push($aErrors, "Your appear to have taken off with zero fuel");
}

//
// Checks a list of helicopters against the given aircraft type
// to determine if the aircraft flown isa helicopter.
//
function isHelicopter($posted)
{
	include_once('helicopter.php');

	// Iterate the helicopter name array. If a match is found, then we have helicopter hours
	foreach ( $g_helicopters as $heloName )
	{
		if ( $posted["AC_TYPE"] == $heloName )
		{
			return true;
		}
	}

	return false;
}

//
// Given Time out and Time in, determine and return total flight time.
//
function calculateFlightTime($flightDate, $timeout, $timein, $bIsHelicopter)
{
	include_once('common.php');
	global $aErrors;

	// An array of flight time information : array("TOTAL" => "", "FIXED_WING" => true, "HELO" => false, "DAY" => "", "NIGHT" => "", "VFR" => "", "IFR" => "");
	$flightTime = $FlightTimeArray;

	// Parse Hours from Minutes
	$timeOutHour  = substr($timeout, 0, 2);
	$timeOutMin   = substr($timeout, 2, 2);
	$timeInHour   = substr($timein, 0, 2);
	$timeInMin    = substr($timein, 2, 2);

	// Convert to integer
	$nStartHour   = intval($timeOutHour);
	$nStartMinute = intval($timeOutMin);
	$nEndHour     = intval($timeInHour);
	$nEndMinute   = intval($timeInMin);

	// Check for valid times
	if ( $nStartHour > 23 || $nEndHour > 23 || $nStartMinute > 59 || $nEndMinute > 59 )
	{
		array_push($aErrors, "The flight times you have given are invalid");
		return "0.0";
	}

	// Parse for start date - Is in format YYYY-MM-DD from POST conversion to SQL date format
	$startYear    = intval(substr($flightDate, 0, 4));
	$startMonth   = intval(substr($flightDate, 5, 2));
	$startDay     = intval(substr($flightDate, 8, 2));

	// End date is same as start date, unless modified below crossing into next day
	$endYear      = $startYear;
	$endMonth     = $startMonth;
	$endDay       = $startDay;

	// If we have crossed into the next day
	if ( $nStartHour > $nEndHour )
	{
		if ( isTomorrowNextYear($endDay, $endMonth, $endYear) )
		{
			$endDay   = 1;
			$endMonth = 1;
			$endYear++;
		}
		else if ( isTomorrowNextMonth($endDay, $endMonth, $endYear) )
		{
			$endDay   = 1;
			$endMonth++;
		}
		else
		{
			$endDay++;
		}
	}

	$startDate  = mktime($nStartHour, $nStartMinute, 0, $startMonth, $startDay, $startYear);
	$endDate    = mktime($nEndHour, $nEndMinute, 0, $endMonth, $endDay, $endYear);
	$diffArray  = date_diff($startDate, $endDate);
	$nTotHour   = $diffArray['hours'];
	$nTotMinute = $diffArray['minutes'];
	$nTotMinute = (($nTotMinute / 60.0) * 100.0) * 0.01;	// Convert minutes to 100ths
	$nFlightTime = $nTotHour + $nTotMinute;					// Combine

	// Fix decimal places to 100ths
	// config.php has decimal places desired, but we will store them in database as .2 decimal
	// and let this option be for display purposes.
	$flightTime["TOTAL"] = sprintf("%2.2f", $nFlightTime);

	//
	// Calculate rest of array members
	//

	// Assume flight time is in a fixed wing aircraft, then check for helicopter
	if ( $bIsHelicopter )
	{
		$flightTime["FIXED_WING"] = false;
		$flightTime["HELO"]       = true;
	}
	else
	{
		$flightTime["FIXED_WING"] = true;
		$flightTime["HELO"]       = false;
	}

	// These are not yet implemented, but present for future versions of APU
	$flightTime["DAY"]   = "";
	$flightTime["NIGHT"] = "";
	$flightTime["VFR"]   = "";
	$flightTime["IFR"]   = "";

	return $flightTime;
}

//
// Determines the amount of fuel used for flight
//
function calculateFuelBurn($fuelout, $fuelin)
{
	include_once('config.php');
	global $aErrors;
	$fuelBurn = 0;

	if ( $bAllowFuelInGTFuelOut )
		$fuelBurn = $fuelout - $fuelin;
	else
	{
		if ( $fuelin > $fuelout )
			array_push($aErrors, "The fuel upon landing is more than the fuel on takeoff");
		else
			$fuelBurn = $fuelout - $fuelin;
	}

	return $fuelBurn;
}

//
// Insert a new or edited PIREP database record into the PIREP table
// and return the previous flight time of an edited PIREP
//
function addPirep($posted, $flightTime, $fuelBurn)
{
	include('config.php');

	// Determine fixed versus helo hours

	$FixedHrs = 0.0;
	$heloHrs  = 0.0;

	if ( $flightTime["FIXED_WING"] )
		$FixedHrs = $flightTime["TOTAL"];
	else
		$heloHrs  = $flightTime["TOTAL"];

	// Build the update or insert query
	if ( $posted['EDIT_MODE'] != 0 )
	{
		// Now update the edited PIREP
		$query  = "UPDATE " .$table_prefix ."PIREP SET ";
		$query .= "PILOT_ID    = '" .$posted["PILOT_ID"]    ."', ";
		$query .= "FLIGHT_DATE = '" .$posted["DATE"]        ."', ";
		$query .= "AC_TYPE     = '" .$posted["AC_TYPE"]     ."', ";
		$query .= "TAIL_NUM    = '" .$posted["TAIL_NUM"]    ."', ";
		$query .= "FLIGHT_NUM  = '" .$posted["FLIGHT_NUM"]  ."', ";
		$query .= "DEPART      = '" .$posted["DEPART_ICAO"] ."', ";
		$query .= "DEST        = '" .$posted["DEST_ICAO"]   ."', ";
		$query .= "TIME_OUT    = '" .$posted["TIME_OUT"]    ."', ";
		$query .= "TIME_IN     = '" .$posted["TIME_IN"]     ."', ";
		$query .= "TIME_FIXED  = '" .$FixedHrs              ."', ";
		$query .= "TIME_HELO   = '" .$heloHrs               ."', ";
		$query .= "FUEL_OUT    = '" .$posted["FUEL_OUT"]    ."', ";
		$query .= "FUEL_IN     = '" .$posted["FUEL_IN"]     ."', ";
		$query .= "FUEL_BURN   = '" .$fuelBurn              ."', ";
		$query .= "PAX         = '" .$posted["PAX"]         ."', ";
		$query .= "CARGO       = '" .$posted["CARGO"]       ."', ";
		$query .= "COMMENTS    = '" .$posted["COMMENTS"]    ."' ";
		$query .= "WHERE id    = "  .$posted['PIREP_ID'];
	}
	else
	{
		$query = "INSERT INTO " .$table_prefix ."PIREP (PILOT_ID,FLIGHT_DATE,AC_TYPE,TAIL_NUM,FLIGHT_NUM,DEPART,DEST,TIME_OUT,TIME_IN,TIME_FIXED,TIME_HELO,FUEL_OUT,FUEL_IN,FUEL_BURN,PAX,CARGO,COMMENTS) VALUES (";
		$query .= "'" .$posted["PILOT_ID"]    ."', ";
		$query .= "'" .$posted["DATE"]        ."', ";
		$query .= "'" .$posted["AC_TYPE"]     ."', ";
		$query .= "'" .$posted["TAIL_NUM"]    ."', ";
		$query .= "'" .$posted["FLIGHT_NUM"]  ."', ";
		$query .= "'" .$posted["DEPART_ICAO"] ."', ";
		$query .= "'" .$posted["DEST_ICAO"]   ."', ";
		$query .= "'" .$posted["TIME_OUT"]    ."', ";
		$query .= "'" .$posted["TIME_IN"]     ."', ";
		$query .= "'" .$FixedHrs              ."', ";
		$query .= "'" .$heloHrs               ."', ";
		$query .= "'" .$posted["FUEL_OUT"]    ."', ";
		$query .= "'" .$posted["FUEL_IN"]     ."', ";
		$query .= "'" .$fuelBurn              ."', ";
		$query .= "'" .$posted["PAX"]         ."', ";
		$query .= "'" .$posted["CARGO"]       ."', ";
		$query .= "'" .$posted["COMMENTS"]    ."'";
		$query .= ")";
	}

	// Perform the update or insert query
	$result = mysql_query($query);
	if ( !$result )
		die("Error: in addPirep() from pirep_submit.php. Adding of new PIREP record failed.<br>Click your browsers back button to try again.<br>If you continue to receive this error, contact the webmaster<br>Failed with mySQL error: " .mysql_error());
}

//
// Updates the pilot record with PIREP values
// First subtracts any previous flight time from an edited PIREP
// before adding any modified pilot flight time
// Checks for and promotes pilot if promotions are enabled in config
//
// function returns true if pilot was promoted
//
function updatePilot($posted, $flightTime)
{
	include_once('config.php');
	include_once('dbcommon.php');
	include_once('commondefs.php');

	global $table_prefix;

	$hoursAC     = 0.0;
	$hoursHelo   = 0.0;
	$totalHours  = 0.0;
	$rank        = 0;
	$promotion   = $PromotionArray;

	// Performing SQL query to get the given pilot by ID
	$query  = 'SELECT RANK_AC, RANK_HELO, HOURS_AC, HOURS_HELO, TOTAL_HRS, TRANSFER_HRS FROM ' .$table_prefix .'PILOTS WHERE PILOT_ID = ' .sqlfix($posted["PILOT_ID"]);
	$result = mysql_query($query);
	if ( !$result )
		die("Error: in updatePilot() from pirep_submit.php. Query for Pilot ID in table PILOTS failed. " .mysql_error());
	$pilot = mysql_fetch_assoc($result);

	//
	// Gather the pilots PIREP's and sum up the hours
	// Best to always just gather and sum, from someone doing an add or edit.
	//

	$pirepArray = gatherPilotsPireps($posted['PILOT_ID']);

	foreach ($pirepArray as $pirep)
	{
		$hoursAC   += $pirep['TIME_FIXED'];
		$hoursHelo += $pirep['TIME_HELO'];
	}
	$totalHours = $hoursAC + $hoursHelo + $pilot['TRANSFER_HRS'];

	//
	// Check for any promotion
	//

	$rank = getFixedWingRank($hoursAC);
	if ( $rank > $pilot['RANK_AC'] )
	{
		$promotion['PROMOTION_A']    = true;
		$promotion['PROMOTION_H']    = false;
		$promotion['PROMOTION_RANK'] = $rank;
	}

	$rank = getHeloRank($hoursHelo);
	if ( $rank > $pilot['RANK_HELO'] )
	{
		$promotion['PROMOTION_A']    = false;
		$promotion['PROMOTION_H']    = true;
		$promotion['PROMOTION_RANK'] = $rank;
	}

	//
	// Update the pilot record
	//

	$todaysDate = getTodayAsSQLDate();
	$query = "UPDATE " .$table_prefix ."PILOTS SET ";

	// Do automatic promotion if enabled
	if ( $bAutomaticPromotions && ($promotion['PROMOTION_A'] || $promotion['PROMOTION_H']) )
	{
		if ( $promotion['PROMOTION_A'] )
		{
			$pilot['RANK_AC']++;
			$query += "RANK_AC='";
			$query += $pilot['RANK_AC'];
			$query += "',";
		}
		else
		{
			$pilot['RANK_HELO']++;
			$query += "RANK_HELO='";
			$query += $pilot['RANK_HELO'];
			$query += "',";
		}
	}

	$query += " HOURS_AC='$hoursAC', HOURS_HELO='$hoursHelo', TOTAL_HRS='$totalHours', LAST_FLY='$todaysDate' WHERE PILOT_ID = " .sqlfix($posted["PILOT_ID"]);
	$result = mysql_query($query);
	if ( !$result )
		die("Error: in updatePilot() from pirep_submit.php. Updating of PILOTS record failed.<br>Click your browsers back button to try again.<br>If you continue to receive this error, contact the webmaster<br>Failed with mySQL error: " . mysql_error());

	return $promotion;
}

//
// Send an email if submitted PIREP to the pilot and optionally to admin email address
//
function sendPirepEmail($posted, $flightTime, $fuelBurn, $promotion)
{
	include('config.php');

	$query  = 'SELECT FIRST_NAME, LAST_NAME, EMAIL FROM ' .$table_prefix .'PILOTS WHERE PILOT_ID = ' .sqlfix($posted["PILOT_ID"]);
	$result = mysql_query($query);
	if ( !$result )
		die("Error: in displayPirep() from pirep_submit.php. Query for Pilot ID in table PILOTS failed. " .mysql_error());
	$pilot = mysql_fetch_array($result, MYSQL_ASSOC);

	$pilotName = $pilot["FIRST_NAME"] ." " .$pilot["LAST_NAME"];
	$email = $pilot["EMAIL"];

	// Send an E-mail to pilot and admin e-mail if not null
	if ( bSendPirepEmailToAdmin )
		$to = $email .", " .$adminEmailAddress;
	else
		$to = $email;

	$subject  = "Pilot PIREP Submitted for " .$pilotName ." " .$posted["PILOT_ID"];

	$message  = "<div align=\"center\">\n";
	$message .= "<table class=\"table_menu\">\n";
	$message .= "	<caption>PIREP Submitted for " .$pilotName ." " .$posted["PILOT_ID"] ."</caption>\n";
	$message .= "<thead><tr><th>&nbsp;</th><th>&nbsp;</th></tr></thead>\n";
	$message .= "<tbody>\n";
	$message .= "	<hr>";
	$message .= "		<tr><td class=\"tableTextRightRedB\">";	$message .= "PILOT ID #";	$message .= "</td><td class=\"tableTextRightRedB\">";	$message .= $posted["PILOT_ID"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Date";			$message .= "</td><td class=\"tableTextRight\">"; 		$message .= $posted["DATE"];   		$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Aircraft Type";$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["AC_TYPE"];		$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Tail #";		$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["TAIL_NUM"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Flight #";		$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["FLIGHT_NUM"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Departure";	$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["DEPART_ICAO"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Destination";	$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["DEST_ICAO"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Time Out";		$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["TIME_OUT"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Time In";		$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["TIME_IN"];		$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRightRedB\">";	$message .= "Flight Time";	$message .= "</td><td class=\"tableTextRightRedB\">";	$message .= $flightTime["TOTAL"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Fuel Out";		$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["FUEL_OUT"];	$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Fuel In";		$message .= "</td><td class=\"tableTextRight\">";    	$message .= $posted["FUEL_IN"];		$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Fuel Burn";	$message .= "</td><td class=\"tableTextRight\">";		$message .= $fuelBurn;				$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "PAX";			$message .= "</td><td class=\"tableTextRight\">";		$message .= $posted["PAX"];			$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Cargo";		$message .= "</td><td class=\"tableTextRight\">";		$message .= $posted["CARGO"];		$message .= "</td></tr>\n";
	$message .= "		<tr><td class=\"tableTextRight\">"; 	$message .= "Comments";		$message .= "</td><td class=\"tableTextRight\">";		$message .= $posted["COMMENTS"];	$message .= "</td></tr>\n";
	$message .= "	</hr>";
	$message .= "</tbody>\n";
	$message .= "<tfoot>\n";
	$message .= "	<tr>\n";
	if ( $bAutomaticPromotions && ($promotion['PROMOTION_A'] || $promotion['PROMOTION_H']) )
	{
		$message .= "		<td colspan=\"2\"><span class=\"tableTextLeft\">You have just been promoted!</span></td>\n";
	}
	else
		$message .= "		<td colspan=\"2\"><span class=\"tableTextLeft\">&nbsp;</span></td>\n";
	$message .= "	</tr>\n";
	$message .= "</tfoot>\n";
	$message .= "</table>\n";
	$message .= "<p>&nbsp;</p>\n";
	$message .= "</div>\n";

	sendEmail("PIREP Submission", $to, $subject, $message);
}

//
//
//
function displayPirep($posted, $flightTime, $fuelBurn, $promotion)
{
	include('config.php');

	// Get the pilots name
	$query  = 'SELECT FIRST_NAME, LAST_NAME FROM ' .$table_prefix .'PILOTS WHERE PILOT_ID = ' .sqlfix($posted["PILOT_ID"]);
	$result = mysql_query($query);
	if ( !$result )
		die("Error: in displayPirep() from pirep_submit.php. Query for Pilot ID in table PILOTS failed. " .mysql_error());
	$pilot = mysql_fetch_array($result, MYSQL_ASSOC);

	$pilotName = $pilot["FIRST_NAME"] ." " .$pilot["LAST_NAME"];

	echo "<table class=\"table_menu\">\n";
	echo "	<caption>PIREP Submitted for " ,$pilotName ." " .$posted["PILOT_ID"] ."</caption>\n";
	echo "<thead><tr><th>&nbsp;</th><th>&nbsp;</th></tr></thead>\n";

	echo "<tbody>\n";
	echo("	<hr>");
	echo("		<tr><td class=\"tableTextRightRedB\">");	echo("PILOT ID #");	   echo("</td><td class=\"tableTextRightRedB\">");	echo($posted["PILOT_ID"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Date");		   echo("</td><td class=\"tableTextRight\">"); 		echo($posted["DATE"]);   		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Aircraft Type"); echo("</td><td class=\"tableTextRight\">");    	echo($posted["AC_TYPE"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Tail #");        echo("</td><td class=\"tableTextRight\">");    	echo($posted["TAIL_NUM"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Flight #");      echo("</td><td class=\"tableTextRight\">");    	echo($posted["FLIGHT_NUM"]);	echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Departure");     echo("</td><td class=\"tableTextRight\">");    	echo($posted["DEPART_ICAO"]);	echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Destination");   echo("</td><td class=\"tableTextRight\">");    	echo($posted["DEST_ICAO"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Time Out");      echo("</td><td class=\"tableTextRight\">");    	echo($posted["TIME_OUT"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Time In");       echo("</td><td class=\"tableTextRight\">");    	echo($posted["TIME_IN"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRightRedB\">"); 	echo("Flight Time");   echo("</td><td class=\"tableTextRightRedB\">");	echo($flightTime["TOTAL"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Fuel Out");      echo("</td><td class=\"tableTextRight\">");    	echo($posted["FUEL_OUT"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Fuel In");       echo("</td><td class=\"tableTextRight\">");    	echo($posted["FUEL_IN"]);		echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Fuel Burn");     echo("</td><td class=\"tableTextRight\">");		echo($fuelBurn);				echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("PAX");           echo("</td><td class=\"tableTextRight\">");		echo($posted["PAX"]);			echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Cargo");         echo("</td><td class=\"tableTextRight\">");		echo($posted["CARGO"]);			echo("</td></tr>\n");
	echo("		<tr><td class=\"tableTextRight\">"); 		echo("Comments");      echo("</td><td class=\"tableTextRight\">");		echo($posted["COMMENTS"]);		echo("</td></tr>\n");
	echo("	</hr>");
	echo "</tbody>\n";

	echo "<tfoot>\n";
	echo "	<tr>\n";
	if ( $bAutomaticPromotions && ($promotion['PROMOTION_A'] || $promotion['PROMOTION_H']) )
	{
		echo "		<td colspan=\"2\"><span class=\"tableTextLeft\">You have just been promoted!</span></td>\n";
	}
	else
		echo "		<td colspan=\"2\"><span class=\"tableTextLeft\">&nbsp;</span></td>\n";
	echo "	</tr>\n";
	echo "</tfoot>\n";
	echo "</table>\n";
	echo "<p>&nbsp;</p>\n";
}

?>
